package cn.itcast.hk;

import org.junit.Test;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class monthys {
    /*
        获取当前时间的前6个月的日期  true [2020-07, 2020-08, 2020-09, 2020-10, 2020-11, 2020-12]
                                    false [7月, 8月, 9月, 10月, 11月, 12月]
    */
    @Test
    public void test(){
        List<String> list = getHalfYearMonth(true);
        System.out.println(list);
    }
    public List<String> getHalfYearMonth(boolean flag) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -5);
        String before_six = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH);// 六个月前
        ArrayList<String> result = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化为年月
        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();
        try {
            min.setTime(sdf.parse(before_six));
            min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
            max.setTime(sdf.parse(sdf.format(new Date())));

            //不含当前月

            /*int month = max.get(Calendar.MONTH);
            max.set(Calendar.MONTH, month-1);*/

            //不含当前月
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
        Calendar curr = min;
        while (curr.before(max)) {
            if (flag) {
                result.add(sdf.format(curr.getTime()));
            } else {
                result.add(curr.get(Calendar.MONTH) + 1 + "月");
            }
            curr.add(Calendar.MONTH, 1);
        }
        /*
         * Calendar curr = max; while (curr.after(min)) {
         * result.add(sd.format(curr.getTime())+"月"); curr.add(Calendar.MONTH, -1); }
         */
        return result;
    }
}
